import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/osc_sp.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/pages/search/search_user_for_pick.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/tweet/osc_tweet_pick_user_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';

class TweetLocalSearchFriends extends StatefulWidget {
  @override
  _TweetLocalSearchFriendsState createState() => _TweetLocalSearchFriendsState();
}

class _TweetLocalSearchFriendsState extends State<TweetLocalSearchFriends> {

  int maxCount = 10;
  int count = 0;

  List<OscUser> localUsers;

  List<OscUser> matchUsers;

  List<OscUser> selectUsers;

  TextEditingController textEditingController;
  FocusNode focusNode;
  String searchName;

  @override
  void initState() {
    super.initState();
    searchName = OscSp().getLastSearchName();
    textEditingController = TextEditingController();
    focusNode = FocusNode();
    localUsers = OscUserManager().getRecentUserList();
    selectUsers = List();
    matchUsers = List();
  }
  @override
  void dispose() {
    super.dispose();
    textEditingController.dispose();
    focusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: "搜索好友",
        actions: <Widget>[
          SmallWidgets.buildAction(
              data: "取消",
              onTap: (){
                Navigator.pop(context);
              },
          ),
        ],
        body: buildBody(),
    );
  }

  buildBody(){
    return ListView(
      children: <Widget>[
        buildSearch(),
        buildLastInput(),
        buildLocalSearchTab(),
        buildLocalSearchUsers(),
        buildNetSearch(),
      ],
    );
  }

  buildSearch(){
    return Container(
      padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_normal),
      margin: EdgeInsets.all(Dimens.gap_view_normal),
      decoration: BoxDecoration(
        color: Colors.white70,
        border: Border.all(color: Colors.black12),
      ),
      child: Row(
        children: <Widget>[
          Image.asset(PdUtil.getImagePath("ic_search"), width: Dimens.view_item_icon_height_small, fit: BoxFit.contain,),
          Expanded(
            child: TextField(
              controller: textEditingController,
              focusNode: focusNode,
              style: MyTextStyle.QUESTION_INPUT_CONTENT,
              decoration: InputDecoration(
                hintText: "搜索",
                hintStyle: MyTextStyle.QUESTION_INPUT_CONTENT_HINT,
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                focusedErrorBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
              ),
              textInputAction: TextInputAction.search,
              onChanged: (text){
                if(!StringUtil.isEmpty(text)){
                  searchName = text;
                  saveLastSearchName();
                  searchLocalUsers();
                  refreshView();
                }
              },
              onSubmitted: (text){

              },
            ),
          ),
        ],
      ),
    );
  }

  buildLastInput(){
    return GestureDetector(
      onTap: (){
        if(!StringUtil.isEmpty(searchName)){
          OscUser user = OscUser(name: searchName);
          popResult(user);
        }
      },
      child: Container(
        alignment: Alignment.centerLeft,
        height: Dimens.view_item_height_biggest,
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal),
        child: Text(StringUtil.isEmpty(searchName)? "" : "@$searchName"),
      ),
    );
  }

  buildLocalSearchTab(){
    return Offstage(
      offstage: matchUsers.length == 0,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_small),
        child: Text("本地搜索结果", style: MyTextStyle.LIST_BODY,),
      ),
    );
  }

  buildLocalSearchUsers(){
    return ListView.separated(
        shrinkWrap: true,
        primary: false,
        itemBuilder: (BuildContext context, int index){
          return buildUserItem(matchUsers.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index){
          return SmallWidgets.buildLine();
        },
        itemCount: matchUsers.length,
    );
  }

  buildUserItem(OscUser user){
    return OscTweetPickUserWidget(
      user: user,
      onTap: (){
        popResult(user);
      },
    );
  }

  buildNetSearch(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
            padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_small),
          child: Text("网络搜索结果", style: MyTextStyle.LIST_BODY,),
        ),
        GestureDetector(
          onTap: (){
            jump2Page(SearchUserForPick(keyword: searchName,));
          },
          child: Container(
              padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_small),
              color: Colors.white,
              alignment: Alignment.centerLeft,
              height: Dimens.view_item_height_big,
              child: Text("网络搜索结果>>>", style: MyTextStyle.USER_LIST_TITLE,),
          ),
        )
      ],
    );
  }

  saveLastSearchName(){
    OscSp().setLastSearchName(searchName);
  }

  searchLocalUsers(){
    if(localUsers != null){
      matchUsers.clear();
      for(OscUser user in localUsers){
        if(user.name.contains(searchName)){
          matchUsers.add(user);
        }
      }
    }
  }

  popResult(OscUser user){
    if(user != null){
      PopResult result = PopResult(id: PopResult.ID_PICK_FRIEND, success: true, extract: {"friend": user});
      Navigator.pop(context, result);
    }
  }

  jump2Page(Widget page){
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result){
      if(result != null && result.success){
        switch(result.id){
          case PopResult.ID_PICK_FRIEND:
            OscUser user = result.extract["friend"];
            popResult(user);
            break;
        }
      }
    });
  }

  refreshView(){
    if(mounted){
      setState(() {

      });
    }
  }
}
